package com.yb.bussiness.goods;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.yb.base.dao.BaseDao;
import com.yb.base.dao.IBaseDao;
import com.yb.domain.goods.TgBrand;
import com.yb.domain.goods.TgGoods;
import com.yb.util.comm.DateTimeUtil;
import com.yb.util.framework.PageUtil;

public class GoodsServiceImpl implements GoodsService {

	private IBaseDao<TgGoods, Long> dao;

	private String FIND_SQL = "SELECT * FROM T_G_GOODS tgg where 1=1 ";

	public GoodsServiceImpl() {
		dao = new BaseDao<TgGoods, Long>(TgGoods.class);
	}

	public void delGoods(Long id) {
		dao.deleteById(id);
	}

	public TgGoods read(Long id) {
		return dao.read(id);
	}

	public void saveOrUpdate(TgGoods goods) {
		if (0 == goods.getId())
			dao.saveEntity(goods);
		else
			dao.update(goods);
	}

	public List<TgGoods> findAll() {
		return dao.findList(FIND_SQL + " ORDER BY CREATETIME");
	}

	public int getCount(Map<String, String> map) {
		try {
			if (map == null || map.size() == 0)
				return 0;
			if (null != map.get("name") && !"".equals(map.get("name")))
				FIND_SQL += "  and name like '%" + map.get("name") + "%'";
			if (null != map.get("typeId") && !"".equals(map.get("typeId")))
				FIND_SQL += "  and typeId = '" + map.get("typeId") + "'";
			if (null != map.get("brandId") && !"".equals(map.get("brandId")))
				FIND_SQL += "  and brandId = '" + map.get("brandId") + "'";
			List<TgGoods> list = dao.findList(FIND_SQL);
			if (list != null && list.size() > 0)
				return list.size();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public PageUtil getList(Map<String, String> map, int page, int limit) {
		PageUtil pu = new PageUtil();
		if (map == null || map.size() == 0)
			return null;
		StringBuffer countSql = new StringBuffer();
		countSql.append("select count(*) from T_G_GOODS tgg where 1=1 ");
		if (null != map.get("name") && !"".equals(map.get("name"))) {
			FIND_SQL += "  and name like '%" + map.get("name") + "%'";
			countSql.append("  and name like '%" + map.get("name") + "%'");
		}
		if (null != map.get("categoryId2")
				&& !"".equals(map.get("categoryId2"))) {
			FIND_SQL += " and categoryid=" + map.get("categoryId2");
			countSql.append(" and categoryid=" + map.get("categoryId2"));
		} else {
			if (null != map.get("categoryId1")
					&& !"".equals(map.get("categoryId1"))) {
				FIND_SQL += " AND EXISTS (SELECT 1 FROM t_g_category tgc WHERE tgc.id = tgg.categoryid AND tgc.pID ="
						+ map.get("categoryId1") + ")";
				countSql
						.append(" AND EXISTS (SELECT 1 FROM t_g_category tgc WHERE tgc.id = tgg.categoryid AND tgc.pID ="
								+ map.get("categoryId1") + ")");
			}
		}
		if (null != map.get("typeId") && !"".equals(map.get("typeId"))) {
			FIND_SQL += "  and typeId = '" + map.get("typeId") + "'";
			countSql.append("  and typeId = '" + map.get("typeId") + "'");
		}
		if (null != map.get("brandId") && !"".equals(map.get("brandId"))) {
			FIND_SQL += "  and brandId = '" + map.get("brandId") + "'";
			countSql.append("  and brandId = '" + map.get("brandId") + "'");
		}
		if (null != map.get("auding") && !"".equals(map.get("auding"))) {
			FIND_SQL += "  and auditingState = " + map.get("auding");
			countSql.append("  and auditingState = " + map.get("auding"));
		}
		List<TgGoods> list = dao.findList(FIND_SQL
				+ " ORDER BY CREATETIME desc limit ?,?", new Object[] {
				(page - 1) * limit, limit });
		List<TgGoods> newlist = null;
		if (list != null && list.size() > 0) {
			newlist = new ArrayList<TgGoods>();
			for (TgGoods tp : list) {
				tp.setCreatetimeString(DateTimeUtil.switchDateToString(tp
						.getCreatetime(), "yyyy-MM-dd HH:mm:ss"));
				tp.setOverTimeString(DateTimeUtil.switchDateToString(tp
						.getOverTime(), "yyyy-MM-dd HH:mm:ss"));
				newlist.add(tp);
			}
		}
		List<Object[]> countList = dao.findObjectArryList(countSql.toString());
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		} else {
			pu.setTotalRecords(0);
		}
		if (null == newlist)
			newlist = new ArrayList<TgGoods>();
		pu.setList(newlist);
		pu.setPageNo(page);
		pu.setPageSize(limit);
		return pu;
	}

	public boolean deleteById(String id) {
		try {
			if ("".equals(id))
				return false;
			String sql = "delete from t_g_goods where id=? ";
			dao.delete(sql, new Object[] { id });
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean deleteByIdString(String idString) {
		boolean isFlag = true;
		if (idString == null || "".equals(idString))
			return false;
		String sql = "";
		String[] delteid = idString.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				sql = "delete from t_g_goods where id=" + delteid[i];
				dao.delete(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return isFlag;
	}

	public TgGoods getById(String id) {
		if ("".equals(id))
			return null;
		String sql = FIND_SQL + " and id=? ";
		try {
			List<TgGoods> list = dao.findList(sql, new Object[] { id });
			if (null != list && list.size() > 0) {
				TgGoods tp = list.get(0);
				tp.setCreatetimeString(DateTimeUtil.switchDateToString(tp
						.getCreatetime(), "yyyy-MM-dd HH:mm:ss"));
				tp.setOverTimeString(DateTimeUtil.switchDateToString(tp
						.getOverTime(), "yyyy-MM-dd HH:mm:ss"));
				return tp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public List findByGoodsId(String value1, String value2) {
		if (!"".equals(value1))
			FIND_SQL += " and brandId = " + value1;
		if (!"".equals(value2))
			FIND_SQL += " and typeId = " + value2;
		return dao.findList(FIND_SQL);
	}

	/**
	 * 表中brandId 存的是商品的id
	 */
	public List<TgGoods> findHotList(Long categoryId, int start, int limit) {
		String sql = "SELECT tgg.* FROM t_g_brand_member tbm ,t_g_goods tgg WHERE tbm.brandId = tgg.id "
				+ "AND EXISTS (SELECT 1 FROM t_g_category tgc WHERE tgc.id = tgg.categoryid AND tgc.pID = ?) and tgg.overTime > now() GROUP BY tgg.id ORDER BY COUNT(tbm.id) desc limit ?,?";
		return dao.findList(sql, new Object[] { categoryId, start, limit });
	}

	public PageUtil findGoodsByCategoryIdORTypeId(Long categoryId, Long typeId,
			int page, int limit) {
		String sql = "select * from t_g_goods where ";
		String countSql = "select count(*) from t_g_goods where ";
		Long tempId;
		if (null != typeId && typeId > 0l) {
			tempId = typeId;
			sql += " typeId = ? ";
			countSql += " typeId = ? ";
		} else {
			tempId = categoryId;
			sql += " categoryid = ? ";
			countSql += " categoryid = ? ";
		}
		sql += " and overTime >= NOW() and auditingState = '1' order by weights desc limit ?,? ";
		countSql += " and overTime >= NOW() and auditingState = '1' ";
		List<TgGoods> goodList = dao.findList(sql, new Object[] { tempId,
				(page - 1) * limit, limit });
		PageUtil pu = new PageUtil();
		pu.setPageNo(page);
		pu.setList(goodList);
		pu.setPageSize(limit);
		List<Object[]> countList = dao.findObjectArryList(countSql,
				new Object[] { tempId });
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		}
		return pu;
	}

	public PageUtil findGoodsByCategoryIdORTypeId(Long categoryId, Long typeId,
			int page, int limit, Long marketId) {
		String sql = "select * from t_g_goods tgg where ";
		String countSql = "select count(*) from t_g_goods tgg where ";
		Long tempId;
		if (null != typeId && typeId > 0l) {
			tempId = typeId;
			sql += " typeId = ? ";
			countSql += " typeId = ? ";
		} else {
			tempId = categoryId;
			sql += " categoryid = ? ";
			countSql += " categoryid = ? ";
		}
		sql += " and EXISTS (select 1 from t_market_brand tmb where tgg.brandId = tmb.brandId and tmb.marketId = ?) and overTime >= NOW() and auditingState = '1'  ";
		countSql += " and EXISTS (select 1 from t_market_brand tmb where tgg.brandId = tmb.brandId and tmb.marketId = ?) and overTime >= NOW() and auditingState = '1'  ";
		sql += " order by weights desc limit ?,? ";
		List<TgGoods> goodList = dao.findList(sql, new Object[] { tempId,
				marketId, (page - 1) * limit, limit });
		PageUtil pu = new PageUtil();
		pu.setPageNo(page);
		pu.setList(goodList);
		pu.setPageSize(limit);
		List<Object[]> countList = dao.findObjectArryList(countSql,
				new Object[] { tempId, marketId });
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		}
		return pu;
	}

	public PageUtil findGoodsByCategoryId(Long categoryId, int page, int limit,
			boolean index) {
		/* and overTime >= now() */
		String sql = "select * from t_g_goods tgg where EXISTS ";
		sql += "(select 1 from t_g_category tgc where tgc.id = tgg.categoryid and tgc.pid = ? ) and auditingState = '1' ";
		String countSql = "select count(*) from t_g_goods tgg where EXISTS ";
		countSql += "(select 1 from t_g_category tgc where tgc.id = tgg.categoryid and tgc.pid = ? ) and auditingState = '1' ";
		if (index)
			sql += " order by weights desc limit ?,? ";
		else
			sql += " order by createtime desc limit ?,? ";
		List<TgGoods> goodList = dao.findList(sql, new Object[] { categoryId,
				(page - 1) * limit, limit });
		PageUtil pu = new PageUtil();
		pu.setPageNo(page);
		pu.setList(goodList);
		pu.setPageSize(limit);
		List<Object[]> countList = dao.findObjectArryList(countSql,
				new Object[] { categoryId });
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		}
		return pu;
	}

	public Integer findGoodsCount(Long categoryId, Long typeId) {
		Integer count = 0;
		String sql = "select count(*) from t_g_brand_member tgbm"
				+ " where EXISTS (select 1 from t_g_goods tgg where tgg.id = tgbm.brandId and";
		Long tempId;
		if (null != typeId && typeId > 0l) {
			tempId = typeId;
			sql += " tgg.typeId = ? ";
		} else {
			tempId = categoryId;
			sql += " tgg.categoryid = ? ";
		}
		sql += ") and tgbm.type = '1'";
		List<Object[]> countList = dao.findObjectArryList(sql,
				new Object[] { tempId });
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			count = new Integer(countAry[0].toString());
		}
		return count;
	}

	// 注 表中brandId 存的是good的主键
	public Integer findGoodsCount(Long goodId) {
		Integer count = 0;
		String sql = "select count(*) from t_g_brand_member tgbm"
				+ " where brandId = ? ";
		List<Object[]> countList = dao.findObjectArryList(sql,
				new Object[] { goodId });
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			count = new Integer(countAry[0].toString());
		}
		return count;
	}

	public void modifyGoodsWeight(Long goodId, Integer weights) {
		String sql = "update t_g_goods set weights = ? where id = ?";
		dao.update(sql, new Object[] { weights, goodId });
	}

	public boolean updateAutingId(String idStr, String autding) {
		try {
			String sql = "update t_g_goods t set t.auditingState=" + autding
					+ " where t.id= " + idStr;
			dao.update(sql);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public PageUtil searchGoods(String name, int page, int limit) {
		PageUtil pu = new PageUtil();
		String sql = "select * from t_g_goods where name like '%" + name
				+ "%' and auditingState = '1' limit ?,?";
		String countSql = "select count(*) from t_g_goods where name like '%"
				+ name + "%' and auditingState = '1' ";
		List<TgGoods> list = dao.findList(sql, new Object[] {
				(page - 1) * limit, limit });
		pu.setList(list);
		pu.setPageNo(page);
		pu.setPageSize(limit);
		List<Object[]> countList = dao.findObjectArryList(countSql);
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		} else {
			pu.setTotalRecords(0);
		}
		return pu;
	}

	//TODO:
	public boolean checkDel(String id) {
		boolean flag = true;
		if (id == null || "".equals(id))
			return true;
		String[] delteid = id.split("_");
		for (int i = 0; i < delteid.length; i++) {
			String sql = "select count(*) from t_pinggou where categoryId = ? and brandId = ?";
			if (bulidResult(sql, new Object[] { delteid[i] }) > 0)
				flag = false;
		}
		return flag;
	}

	private int bulidResult(String sql, Object[] conditionAry) {
		int count = 0;
		List<Object[]> list = dao.findObjectArryList(sql, conditionAry);
		Object[] objAry = list.get(0);
		count = new Integer(objAry[0].toString());
		return count;
	}
}
